home *** CD-ROM | disk | FTP | other *** search
- /****i* SOURCE_FILE/INFO
- *
- * NAME
- * MessageFormat.js
- *
- * USAGE
- * Part of Netobjects JavaScript Library.
- *
- * COPYRIGHT
- * Copyright ⌐ 2000-2005 Website Pros, Inc.
- * All Rights Reserved.
- *
- * This is an unpublished work protected by Website Pros, Inc.
- * as a trade secret, and is not to be used or disclosed except as
- * expressly provided in a written license agreement executed by
- * you and Website Pros, Inc.
- *
- * <copyright@websitepros.com>
- *
- * NOTES
- * JavaScript code.
- *
- *****/
- if (!IS.isModuleInitialized("IS.NOF.TEXT.MessageFormat"))
- {
-
- /****h* NOF_JavaScript_Library/NOF.TEXT.MessageFormat
- *
- * NAME
- * NOF.TEXT.MessageFormat
- *
- * DESCRIPTION
- *
- * <code>MessageFormat</code> is a class which provides a simple way to
- * format a text using parameters.
- * Usage sample:
- * var myPattern = "{0} is smaller than {1}, thus {1} is greater than {0}";
- * var myParams = ["the number 3", "the number 4"];
- * var str = NOF.TEXT.MessageFormat.format(myPattern, myParams);
- * alert( str );
- *
- * External dependencies: none.
- ****/
-
- /**
- * Constructor
- **/
- function TEXT_MessageFormat() {
- this.__proto__ = TEXT_MessageFormat.prototype;
- }
- {
- var method = TEXT_MessageFormat.prototype;
-
- /**
- * static method used to format a message
- * @param pattern the pattern for this message format
- * @param params an array of objects (strings) to be formatted and substituted.
- * @return the string obtained by replacing {x} sequences from the pattern with
- * params[x] values, where x are indices from 0 to params length
- **/
- method.format = function (/*string*/ pattern, /*Array*/ params) {
- if (pattern == null) return null;
- if (params == null) return pattern;
-
- var parameters;
-
- //if (params.constructor == Array) {
- //the previous line should have been working, but it doesn't!
- //the next lines makes the difference between strings and arrays
- //if ( (""+params.constructor).indexOf("function Array()") > -1) {
- if (params.join) {
- parameters = params;
- } else {
- //probably the method was called in the old fashion way, like this:
- //NOF.TEXT.MessageFormat.format("{0} bla bla {1}", "BLA", "ALB");
- parameters = new Array();
- for (var i = 1; i < arguments.length; i++) {
- parameters[i - 1] = arguments[i];
- }
- }
-
- var str = pattern;
- var substr = null;
- var j;
- for (var i=0; i < parameters.length; i++) {
- substr = "{" + i + "}";
- while (true) {
- j = str.indexOf(substr);
- if (j < 0) break;
- str = str.substring(0,j) + parameters[i] + str.substring(j+substr.length, str.length);
- }
- }
- return str;
- }
- }
- // add it to NOF.TEXT namespace
- TEXT.__proto__.MessageFormat = new TEXT_MessageFormat();
- }